package com.company.proxy.v07;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Random;

public class Tank implements MoveAble {
    /*
    模拟坦克的移动时间
     */
    @Override
    public void move() {
        System.out.println("tank moving calacalacala");
        try {
            Thread.sleep(new Random().nextInt(10000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Tank tank = new Tank();

        //reflection 反射 通过二进制字节码分析类的属性和方法

        // InvocationHandler被调用时的处理器
//        MoveAble m = (MoveAble) Proxy.newProxyInstance(Tank.class.getClassLoader(), new Class[]{MoveAble.class},
//                new InvocationHandler() {
//                    @Override
//                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                        System.out.println("method"+method.getName()+"start....");
//                        Object o = method.invoke(tank,args);
//                        System.out.println("method"+method.getName()+"end!!!");
//                        return o;
//                    }
//                });
        MoveAble m = (MoveAble) Proxy.newProxyInstance(Tank.class.getClassLoader(), new Class[]{MoveAble.class},
                new LogHandler(tank));
        m.move();
    }
}

class LogHandler implements InvocationHandler {
    Tank tank;

    public LogHandler(Tank tank) {
        this.tank = tank;
    }


    //invoke 在move方法的时候被调用

    //method :调用的方法move， args调用这个方法传进来的参数 proxy生成的代理对象在这里就是m
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("method" + method.getName() + "start....");
        //调用被代理对象的方法
        Object o = method.invoke(tank, args);
        System.out.println("method" + method.getName() + "end!!!");
        return o;
    }
}

interface MoveAble {
    void move();
}